import 'package:cached_network_image/cached_network_image.dart';
import 'package:common_utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';
import 'package:get/get.dart';
import 'package:nft_shop/box/page/Invitebox/Invite_box_page.dart';
import 'package:nft_shop/login/controller/user_controller.dart';
import 'package:nft_shop/login/page/login_page.dart';
import 'package:nft_shop/my/model/models.dart';
import 'package:nft_shop/my/page/notice/home_announcement_page.dart';
import 'package:nft_shop/my/page/notice/website_del.dart';
import 'package:nft_shop/res/global.dart';
import 'package:nft_shop/sift/conteroller/sift_conteroller.dart';
import 'package:nft_shop/sift/page/sift_list_page.dart';
import 'package:nft_shop/sift/page/sift_notice_page.dart';
import 'package:nft_shop/util/route_observer.dart';
import 'package:nft_shop/widgets/custom_underline_tabIndicator.dart';
import 'package:nft_shop/widgets/load_image.dart';
import 'package:nft_shop/widgets/my_app_bar.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class SiftPage extends StatefulWidget {
  @override
  State<SiftPage> createState() => _SiftPageState();
}

class _SiftPageState extends State<SiftPage>
    with
        SingleTickerProviderStateMixin,
        AutomaticKeepAliveClientMixin,
        RouteAware {
  TabController? _tabController;
  final PageController _pageController = PageController(initialPage: 0);
  SiftConteroller _conteroller = SiftConteroller.to;

  ///刷新组件
  RefreshController refreshController =
      RefreshController(initialRefresh: false);

  /// 分页第一页页码
  static const int pageNumFirst = 1;

  /// 当前第几页
  int currentPageNum = pageNumFirst;

  /// 分页条目数量
  int pageSize = 15;

  /// 页面数据
  List list = [];

  @override
  bool get wantKeepAlive => true;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    RouteUtils.routeObserver
        .subscribe(this, ModalRoute.of(context) as PageRoute);
  }

  @override
  void dispose() {
    RouteUtils.routeObserver.unsubscribe(this);
    super.dispose();
    _tabController?.dispose();
  }

//回到当前页面
  @override
  void didPopNext() {
    print("首页返回刷新了---");
    SiftConteroller.to.getDataList();
  }

  // //获取数据
  // Future<List> loadData({int? pageNum}) async {
  //   return await ServiceRepository.goodsSpecialList(page: 1, pageSize:pageSize, isHot:1,isNow:0, type:0);
  //
  // }
  //
  // /// 下拉刷新
  // ///
  // /// [init] 是否是第一次加载
  // /// true:  Error时,需要跳转页面
  // /// false: Error时,不需要跳转页面,直接给出提示
  // Future<List?> refresh({bool init = false}) async {
  //   try {
  //     currentPageNum = pageNumFirst;
  //     var data = await loadData(pageNum: pageNumFirst);
  //     if (data.isEmpty) {
  //       refreshController.refreshCompleted(resetFooterState: true);
  //       list.clear();
  //       // status = LoadStatusType.empty;
  //     } else {
  //       list.clear();
  //       list.addAll(data);
  //       refreshController.refreshCompleted();
  //       // 小于分页的数量,禁止上拉加载更多
  //       if (data.length < pageSize) {
  //         refreshController.loadNoData();
  //       } else {
  //         //防止上次上拉加载更多失败,需要重置状态
  //         refreshController.loadComplete();
  //       }
  //       // status = LoadStatusType.success;
  //     }
  //     return data;
  //   } catch (e, s) {
  //     /// 页面已经加载了数据,如果刷新报错,不应该直接跳转错误页面
  //     /// 而是显示之前的页面数据.给出错误提示
  //     if (init) list.clear();
  //     refreshController.refreshFailed();
  //     // status = LoadStatusType.empty;
  //     // setError(e, s);
  //     return null;
  //   }
  // }
  //
  // /// 上拉加载更多
  // Future<List?> loadMore() async {
  //   try {
  //     var data = await loadData(pageNum: ++currentPageNum);
  //     if (data.isEmpty) {
  //       currentPageNum--;
  //       refreshController.loadNoData();
  //     } else {
  //       list.addAll(data);
  //       if (data.length < pageSize) {
  //         refreshController.loadNoData();
  //       } else {
  //         refreshController.loadComplete();
  //       }
  //       setState(() {
  //
  //       });
  //     }
  //     return data;
  //   } catch (e, s) {
  //     currentPageNum--;
  //     refreshController.loadFailed();
  //     return null;
  //   }
  // }

  @override
  Widget build(BuildContext context) {
    print("首页刷新--");
    if (_tabController == null) {
      // _tabController = TabController(vsync: this, length: 3);
      _tabController = TabController(vsync: this, length: 2);
    }

    return Scaffold(
      appBar: MyAppBar(
        isBack: false,
        centerTitle: "首页",
      ),
      body: NestedScrollView(
        key: const Key('home_list'),
        physics: const ClampingScrollPhysics(),
        headerSliverBuilder: (context, innerBoxIsScrolled) =>
            _sliverBuilder(context),
        body: GetBuilder<SiftConteroller>(
          id: SiftConteroller.siftPageID,
          builder: (logic) {
            return PageView.builder(
              // itemCount: 3,
              itemCount: 2,
              onPageChanged: _onPageChange,
              controller: _pageController,
              itemBuilder: (_, index) => SiftListPage(index: index),
            );
          },
        ),
      ),
    );
  }

  ///置顶
  List<Widget> _sliverBuilder(BuildContext context) {
    return <Widget>[
      //头部
      SliverToBoxAdapter(
        child: Column(
          children: [
            ///轮播图
            swiperView(),
            SizedBox(
              height: 13,
            ),
          ],
        ),
      ),
      //选项卡
      SliverPersistentHeader(
        pinned: true,
        floating: true,
        delegate: SliverAppBarDelegate(
          DecoratedBox(
            decoration: BoxDecoration(color: Global.kTheme.colorBackground1),
            child: tabsWidget(),
          ),
          44.0,
        ),
      ),
    ];
  }

  ///轮播图
  Widget swiperView() {
    return GetBuilder<SiftConteroller>(
      id: SiftConteroller.bannersID,
      builder: (logic) {
        return Container(
          height: (Get.width - 28) * 360 / 750,
          child: Swiper(
            itemCount: _conteroller.banners.length,
            loop: false,
            autoplay: true,
            autoplayDelay: 5000,
            pagination: SwiperPagination(
                margin: EdgeInsets.only(bottom: 10),
                builder: CustomPaginationBuilder(
                  color: Colors.white.withOpacity(0.5),
                  activeColor: Colors.white,
                )),
            itemBuilder: (_, index) {
              Article model = _conteroller.banners[index];
              return Container(
                margin: EdgeInsets.symmetric(horizontal: 14),
                child: ClipRRect(
                    borderRadius: BorderRadius.circular(10),
                    child: BannerImage(model.thumb ?? "")),
              );
            },
            onTap: (index) {
              Article model = _conteroller.banners[index];
              if (model.jumpType == 1) {
                // Get.to(InviteBoxPage(ID: "5")); //model.jumpContent??"",
                if (UserController.to.isLogin) {
                  //跳转类型
                  Get.to(InviteBoxPage(ID: model.jumpContent ?? ""));
                } else {
                  Get.to(LoginPage());
                }
              } else {
                if (ObjectUtil.isNotEmpty(model.jumpContent)) {
                  Get.to(WebsiteDel(
                      (ObjectUtil.isEmpty(model.title) ? "详情" : model.title!),
                      model.jumpContent!));
                }
              }
            },
          ),
        );
      },
    );
  }

  ///公告
  Widget noticeView() {
    return GetBuilder<SiftConteroller>(
      id: SiftConteroller.topArticlesID,
      builder: (locgin) {
        return Container(
          height: 36,
          decoration: BoxDecoration(
            color: Global.kTheme.colorBackground2,
            borderRadius: BorderRadius.circular(4),
          ),
          margin: EdgeInsets.symmetric(horizontal: 14),
          padding: EdgeInsets.symmetric(horizontal: 9),
          child: Row(
            children: [
              LoadAssetImage(
                "sift_notice",
                width: 14,
                height: 13,
              ),
              SizedBox(
                width: 10,
              ),
              _conteroller.topArticles.length == 0
                  ? Expanded(
                      child: Container(
                        height: 40,
                        padding: EdgeInsets.symmetric(horizontal: 3),
                      ),
                    )
                  : Expanded(
                      child: Container(
                        height: 40,
                        padding: EdgeInsets.symmetric(horizontal: 3),
                        child: Swiper(
                          itemCount: _conteroller.topArticles.length,
                          loop: true,
                          autoplay: true,
                          autoplayDelay: 4000,
                          scrollDirection: Axis.vertical,
                          itemBuilder: (_, index) {
                            Article model = _conteroller.topArticles[index];
                            return Align(
                                alignment: Alignment.centerLeft,
                                child: Text(
                                  model.title ?? "",
                                  style: TextStyle(
                                      color: Global.kTheme.textPrimary2,
                                      fontSize: 12),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ));
                          },
                          onTap: (index) {
                            Article model = _conteroller.topArticles[index];
                            Get.to(AnnouncementPage(
                              title: model.title ?? "",
                              content: model.content ?? "",
                            ));
                          },
                        ),
                      ),
                    ),
              InkWell(
                  onTap: () => Get.to(SiftNoticePage()),
                  child: Icon(
                    Icons.more_horiz_rounded,
                    color: Color(0xFF14181F),
                  )),
            ],
          ),
        );
      },
    );
  }

  ///选项卡
  Widget tabsWidget() {
    return TabBar(
      isScrollable: true,
      controller: _tabController,
      labelStyle: TextStyle(
        fontSize: 18,
        fontFamily: Global.mySemiboldFont,
      ),
      unselectedLabelStyle: TextStyle(
        fontSize: 16,
        fontFamily: Global.mySemiboldFont,
      ),
      indicatorSize: TabBarIndicatorSize.label,
      unselectedLabelColor: Global.kTheme.textPrimary3,
      labelColor: Global.kTheme.textPrimary4,
      indicatorPadding: EdgeInsets.only(bottom: 2, left: 9, right: 9),
      indicator: CustomUnderlineTabIndicator(
          borderSide: BorderSide(
        color: Global.kTheme.textPrimary4,
        width: 3,
      )),
      tabs: const <Widget>[
        Tab(
          text: "热门",
        ),
        // Tab(
        //   text: "近期",
        // ),
        Tab(
          text: "预售",
        ),
      ],
      onTap: (index) {
        if (!mounted) {
          return;
        }
        _pageController.jumpToPage(index);
        _conteroller.currentPage = index;
      },
    );
  }

  ///imageWidget
  Widget BannerImage(String url, {BoxFit? fit = BoxFit.fill}) {
    return CachedNetworkImage(
        imageUrl: url,
        placeholder: (context, url) =>
            Center(child: CupertinoActivityIndicator()),
        errorWidget: (context, url, error) => Icon(Icons.error),
        fit: fit);
  }

  void _onPageChange(int index) {
    _tabController?.animateTo(index);
    _conteroller.currentPage = index;
  }
}

class SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
  SliverAppBarDelegate(this.widget, this.height);

  final Widget widget;
  final double height;

  // minHeight 和 maxHeight 的值设置为相同时，header就不会收缩了
  @override
  double get minExtent => height;

  @override
  double get maxExtent => height;

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return widget;
  }

  @override
  bool shouldRebuild(SliverAppBarDelegate oldDelegate) {
    return true;
  }
}

class CustomPaginationBuilder extends SwiperPlugin {
  final Color? activeColor;
  final Color? color;
  final Size activeSize;
  final Size size;
  final double space;
  final Key? key;

  const CustomPaginationBuilder(
      {this.activeColor,
      this.color,
      this.key,
      this.size: const Size(8.0, 4.0),
      this.activeSize: const Size(12.0, 4.0),
      this.space: 4.0});

  @override
  Widget build(BuildContext context, SwiperPluginConfig config) {
    ThemeData themeData = Theme.of(context);
    Color activeColor = this.activeColor ?? themeData.primaryColor;
    Color color = this.color ?? themeData.scaffoldBackgroundColor;
    List<Widget> list = [];
    int itemCount = config.itemCount;
    int activeIndex = config.activeIndex;

    for (int i = 0; i < itemCount; ++i) {
      bool active = i == activeIndex;
      Size size = active ? this.activeSize : this.size;
      list.add(Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(2),
          color: active ? activeColor : color,
        ),
        width: size.width,
        height: size.height,
        key: Key("pagination_$i"),
        margin: EdgeInsets.all(space),
      ));
    }
    if (itemCount == 1) {
      return Container();
    }
    return Container(
      width: double.infinity,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        key: key,
        mainAxisSize: MainAxisSize.min,
        children: list,
      ),
    );
  }
}
